﻿var mathJQ;
window.mathJQ = mathJQ;

$(document).ready(function () {
    if (!mathJQ) {
        mathJQ = new MathJQ();
    }
});

function MathJQ() {
    this.latexSource = document.getElementById('latex-source');
    this.latexMath = document.getElementById('editable-math');
    this.FormulasPanelsLoaded = [];
    this.initialize();
}

MathJQ.prototype = {
    initialize: function () {

        this.initializeLaTexSource();
        this.initializeMath();
        //this.initializeAccordions();
        this.initializeNotAccordions();
    },
    initializeNotAccordions: function(){
        $.getScript( "../jq/js/mathquill/mathquill.js", function( data, textStatus, jqxhr ) {
          
        });
        /*$.getScript( "../jq/js/b.min.js", function( data, textStatus, jqxhr ) {
          
        }); */
        $("#basicmath").load("../jq/formulas/RELATION_SYMBOLS" +".html", function () {
              mathJQ.initializeFormulaSymbols("basicmath");
        });
        $("#tab-matrix").on("click",function(){
            $("#matrix").load("../jq/formulas/MATRIX_SYMBOLS" +".html", function () {
              mathJQ.initializeFormulaSymbols("matrix");
            });
        });
        
        $("#arrow").load("../jq/formulas/ARROW_SYMBOLS" +".html", function () {
              mathJQ.initializeFormulaSymbols("arrow");
        });
        $("#cases").load("../jq/formulas/CASES_SYMBOLS" +".html", function () {
              mathJQ.initializeFormulaSymbols("cases");
        });
        $("#integral").load("../jq/formulas/INTEGRAL_SYMBOLS" +".html", function () {
              mathJQ.initializeFormulaSymbols("integral");
        });
        $("#calculus").load("../jq/formulas/CALCULUS" +".html", function () {
              mathJQ.initializeFormulaSymbols("calculus");
        });
        $("#logarit").load("../jq/formulas/FONCTION_SYMBOLS" +".html", function () {
              mathJQ.initializeFormulaSymbols("logarit");
        });
        $("#symbols").load("../jq/formulas/OPERATOR_SYMBOLS" +".html", function () {
              mathJQ.initializeFormulaSymbols("symbols");
        });
         $("#more").load("../jq/formulas/L_U_GREEK_CHAR" +".html", function () {
              mathJQ.initializeFormulaSymbols("more");
        });

          $("#layout").load("../jq/formulas/LAYOUTS" +".html", function () {
              mathJQ.initializeFormulaSymbols("layout");
        });
    },
    initializeAccordions: function () {
        var mathJQ = this;
        $("#aaFormulas").accordion({
            onSelect: function (title) {
                var fPanel = $("#aaFormulas").accordion("getSelected");
                if (fPanel) {
                    var fPanelID = $(fPanel).attr("id");
                    if (mathJQ.FormulasPanelsLoaded.indexOf(fPanelID) == -1)
                    {
                        mathJQ.FormulasPanelsLoaded[mathJQ.FormulasPanelsLoaded.length] = fPanelID;
                        $(fPanel).load("./jq/formulas/" + fPanelID + ".html", function () {
                            mathJQ.initializeFormulaSymbols(fPanelID);
                        });
                    }
                }
                
            }
        });
        var p = $("#aaFormulas").accordion('getSelected');
        if (p) {
            p.panel('collapse', false);
        }
    },
    initializeFormulaSymbols: function (PanelID) {
        var mathJQ = this;

        function getSymbol(obj) {
            if (typeof ($(obj).attr("lbegin")) != "undefined" && typeof ($(obj).attr("lend")) != "undefined") {
                return  $(obj).attr("t");
            }
            else if (typeof ($(obj).attr("latex")) != "undefined") {
                return $(obj).attr("t");
            }
            else {
                return '';
            }
        }

        $("#" + PanelID).find(" a.s").addClass("easyui-tooltip").attr("title", function (index, attr) {
            return getSymbol(this);
        }).mouseover(function (event) {
            $("#divInformation").html(getSymbol(this));
        }).mouseout(function (event) {
            $("#divInformation").html("&nbsp;");
        }).click(function (event) {
            event.preventDefault();
            if (typeof ($(this).attr("lbegin")) != "undefined" && typeof ($(this).attr("lend")) != "undefined") {

                mathJQ.tag($(this).attr("lbegin"), $(this).attr("lend"),$(this).attr("jump"));
            }
            else if (typeof ($(this).attr("latex")) != "undefined") {
                mathJQ.insert($(this).attr("latex"),$(this).attr("jump"));
            }
            else {
                //$.messager.show({
                //    title: "<span class='rtl-title-withicon'>" + mathJQ.getLocalText("INFORMATION") + "</span>",
                //    msg: mathJQ.getLocalText("NO_LATEX")
                //});
            }
        });
        MathJax.Hub.Queue(["Typeset", MathJax.Hub, PanelID]);
    },
    initializeMath: function () {
        var mathJQ = this;
        $('#editable-math').bind('keydown keypress', function () {
            mathJQ.EditableMathChange();
        }).keydown().focus();
    },
    initializeLaTexSource: function () {
        var mathJQ = this;
        $('#latex-source').bind('keydown keypress paste', function () {
            mathJQ.SourceLaTexChange();
        });
    },
    printTree: function (html) {
        html = html.match(/<[a-z]+|<\/[a-z]+>|./ig);
        if (!html) return '';
        var indent = '\n', tree = [];
        for (var i = 0; i < html.length; i += 1) {
            var token = html[i];
            if (token.charAt(0) === '<') {
                if (token.charAt(1) === '/') { //dedent on close tag
                    indent = indent.slice(0, -2);
                    if (html[i + 1] && html[i + 1].slice(0, 2) === '</') //but maintain indent for close tags that come after other close tags
                        token += indent.slice(0, -2);
                }
                else { //indent on open tag
                    tree.push(indent);
                    indent += '  ';
                }

                token = token.toLowerCase();
            }

            tree.push(token);
        }
        return tree.join('').slice(1);
    },
    insert: function (b,jump) {
        
        $('#editable-math').mathquill('write', b , jump).find('textarea').focus();
        this.EditableMathChange();
    },
    tag: function (b, a,jump) { 
        b = b || null;
        a = a || b;
        if (!b || !a) {
            return;
        }
        this.insert(b+a,jump);

    },
    EditableMathChange: function () {
        setTimeout(function () {
            var latex = $('#editable-math').mathquill('latex');                
            $('#latex-source').val(latex);
        },500);
    },
    SourceLaTexChange: function () {
        var oldtext = $('#latex-source').val();
        setTimeout(function () {
            var newtext = $('#latex-source').val();
            if (newtext !== oldtext) {
                $('#editable-math').mathquill('latex', newtext);
            }
        });
    },
    UpdateVisualMath: function () {
        setTimeout(function () {
            $('#editable-math').mathquill('latex', $('#latex-source').val());
        });
    }
};

